package com.health.yb.core.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.mail.GlobalMailAccount;
import cn.hutool.extra.mail.MailAccount;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Collection;
import java.util.Properties;

/**
 * @author ping zhang
 * @create 2020-01-09 10:38
 **/

public class MailUtil {

    public static void sendMsg(Collection<String> tos, String subject, String content, boolean isHtml) throws Exception {
        MailAccount account = GlobalMailAccount.INSTANCE.getAccount();
        Properties prop = new Properties();
        prop.setProperty("mail.host", account.getHost());
        prop.setProperty("mail.smtp.auth", "true");

        Authenticator aut = new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(account.getUser(), account.getPass());//由于涉及隐私就用拼音代替了

            }
        };
        Session session = Session.getInstance(prop, aut);
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(account.getFrom()));//sender
        Address[] addresses = new InternetAddress[tos.size()];
        String[] array = tos.toArray(new String[]{});
        for (int i = 0; i < tos.size(); i++) {
            addresses[0] = new InternetAddress(array[i]);
        }
        msg.setRecipients(Message.RecipientType.TO, addresses);//recipients
        msg.setSubject(subject);
        msg.setContent(content, StrUtil.format("text/{}; charset={}", new Object[]{isHtml ? "html" : "plain", account.getCharset()}));
        Transport.send(msg);
    }
}
